﻿using System;
using System.Collections;
using System.Data;
using Model.Entity;


namespace DAL
{
    public class BorrowDAL
    {
        private BaseDAL baseDal = null;
        public readonly static long FAIL_COUNT = -1;
        private readonly static String BORROW_COUNT_HQL = "select count(*) from Borrow b where b.user.id=?",
            GET_BORROW_BY_RFID_HQL = "select b from Borrow b where b.rfid.rfid=?",
            GET_BORROW_BY_USER_SQL = "select * from _Borrow bo inner join _Rfid r on bo.rfid=r.rfid inner join _Book b on r.bookIsbn=b.isbn where bo.isReturn='false' and bo.userId=@0",
            CAN_RETURN_HQL = "select b from Borrow b inner join b.rfid where b.isReturn=false and b.rfid.rfid=?",
            RENEW_ALL_UPDATE_HQL = "update Borrow bo set bo.renewCount=(select buffer.renewCount + 1 from Borrow buffer where buffer.id=bo.id), bo.shouldReturnDate=? where bo.isReturn=false and bo.renewCount<(select buffer.user.userType.enableRenewCount from Borrow buffer where buffer.id=bo.id) and bo.shouldReturnDate>=? and bo.user.id=?";

        public BorrowDAL()
        {
            baseDal = new BaseDAL();
        }

        public int save(Borrow borrow)
        {
            return (int)baseDal.save(borrow);
        }

        public void update(Borrow borrow)
        {
            baseDal.update(borrow);
        }

        public long getCountByUser(int userId)
        {
            foreach (long result in baseDal.executeHql(BORROW_COUNT_HQL, userId))
            {
                return result;
            }
            return FAIL_COUNT;
        }

        public Borrow getByRfidWithoutReturn(String rfid)
        {
            foreach (Borrow result in baseDal.executeHql(GET_BORROW_BY_RFID_HQL + " and b.isReturn=?", rfid, false))
            {
                return result;
            }
            return null;
        }

        public Borrow getByRfid(String rfid)
        {
            foreach (Borrow result in baseDal.executeHql(GET_BORROW_BY_RFID_HQL, rfid))
            {
                return result;
            }
            return null;
        }

        public DataTable getByUserT(int userId)
        {
            return baseDal.executeSql(GET_BORROW_BY_USER_SQL, userId);
        }

        public Borrow canReturn(String rfid)
        {
            foreach (Borrow result in baseDal.executeHql(CAN_RETURN_HQL, rfid))
            {
                return result;
            }
            return null;
        }

        public int renewAllByUser(int userId, DateTime shouldReturnDate)
        {
            return baseDal.executeUpdateHql(RENEW_ALL_UPDATE_HQL, shouldReturnDate, DateTime.Now, userId);
        }
    }
}
